package com.fc.common.util;



import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @author 作者相关信息
 * @version 1.0 版本信息
 * @description 类的描述
 * @date 2021/11/23 08:33
 */
public class FileUtil {
    public static void copyFile(InputStream is, OutputStream os){
        try {
            byte[] bytes = new byte[1024];
            int count = -1;
            //read方法返回-1表示没有内容可读了
            while( (count=is.read(bytes)) != -1){
                os.write(bytes,0,count);//将文件放入流中
                os.flush();//将流中的内容写到文件中
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void close(InputStream is, OutputStream os){
        if(os != null ){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //两个流一定要分开关闭
            if( is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }

    public static boolean checkIsImageFile(String fileName){
        if(!fileName.endsWith(".jpg")&&!fileName.endsWith(".jpeg")&&!fileName.endsWith(".png")&&
                !fileName.endsWith(".bmp")&&!fileName.endsWith(".JPEG")&&!fileName.endsWith(".JPG")
                &&!fileName.endsWith(".PNG")&&!fileName.endsWith(".BMP") ){
            return  false;
        }else{
            return  true;
        }
    }

    public static String encodeImageToBase64(MultipartFile file){
        ByteArrayOutputStream os = null;
        InputStream is = null;
        try {
            is = file.getInputStream();
            os = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int count = -1;
            //read方法返回-1表示没有内容可读了
            while ((count = is.read(bytes)) != -1) {
                os.write(bytes, 0, count);//将文件放入流中
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String encode = encoder.encode(os.toByteArray());
        close(is,os);
        return encode ;// 返回Base64编码过的字节数组字符串
    }

    public static void decodeBase64ToImage(String base64, String path, String fileName){
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            FileOutputStream write = new FileOutputStream(new File(path + fileName));
            byte[] decoderBytes = decoder.decodeBuffer(base64);
            write.write(decoderBytes);
            write.flush();
            write.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
